package com.shakespace.artofandroid.chapter02.contentprovider


import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.net.Uri
import android.util.Log
import com.shakespace.firstlinecode.global.TAG

class BookProvider : ContentProvider() {

    private lateinit var database: SQLiteDatabase

    override fun onCreate(): Boolean {
        Log.e(this.TAG, "onCreate: ${Thread.currentThread().name}")
        database = DBOpenHelper(context).writableDatabase


        return false
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
        Log.e(this.TAG, "delete: ${Thread.currentThread().name}")
        var count = 0
        getTableName(uri).takeIf {
            it.isNotEmpty()
        }?.let {
            count = database.delete(it, selection, selectionArgs)
            if (count > 0) {
                context?.contentResolver?.notifyChange(uri, null)
            }
        }
        return count
    }

    override fun getType(uri: Uri): String? {
        Log.e(this.TAG, "getType: ${Thread.currentThread().name}")

        return ""
    }

    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        Log.e(this.TAG, "insert: ${Thread.currentThread().name}")
        getTableName(uri).takeIf {
            it.isNotEmpty()
        }?.let { tableName: String ->
            database.insert(tableName, null, values)
            context?.contentResolver?.notifyChange(uri, null)
        }
        return uri
    }

    override fun query(
        uri: Uri, projection: Array<String>?, selection: String?,
        selectionArgs: Array<String>?, sortOrder: String?
    ): Cursor? {
        Log.e(this.TAG, "query: ${Thread.currentThread().name}")

        val tableName = getTableName(uri)
        if (tableName.isNotEmpty()) {
            return database.query(tableName, projection, selection, selectionArgs, null, sortOrder, null)
        }
        return null
    }

    override fun update(
        uri: Uri, values: ContentValues?, selection: String?,
        selectionArgs: Array<String>?
    ): Int {
//        uri.authority
        Log.e(this.TAG, "update: ${Thread.currentThread().name}")
        getTableName(uri).takeIf {
            it.isNotEmpty()
        }?.let { tableName ->
            val row = database.update(tableName, values, selection, selectionArgs)
            if (row > 0) {
                context?.contentResolver?.notifyChange(uri, null)
                return row
            }
        }
        return 0
    }


    fun getTableName(uri: Uri): String {
        return when (uriMatcher.match(uri)) {
            BOOK_URI_CODE -> "book"
            USER_URI_CODE -> "user"
            else -> ""
        }
    }

    companion object {

        val uriMatcher = UriMatcher(UriMatcher.NO_MATCH)

        val AUTHORITY = "com.shakespace.artofandroid.book.provider"

        val BOOK_URI_CODE = 0
        val USER_URI_CODE = 1

        val BOOK_CONTENT_URI = Uri.parse("content://$AUTHORITY/book")
        val USER_CONTENT_URI = Uri.parse("content://$AUTHORITY/user")

        init {
            uriMatcher.addURI(AUTHORITY, "book", BOOK_URI_CODE)
            uriMatcher.addURI(AUTHORITY, "user", USER_URI_CODE)

            /**
             * after call addUri , uriCode will match will uri
             * if call match , will get uriCode
             */
//            val uriCode = uriMatcher.match(Uri.parse("content://$AUTHORITY/book"))
        }


    }

}
